package com.tmc.util;

import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import javax.imageio.ImageIO;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.ClientAnchor;
import org.apache.poi.ss.usermodel.Drawing;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.xssf.usermodel.XSSFClientAnchor;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class ExcelUtil {

	public static void main(String[] args) throws Exception {
		String path = "C:/Users/legion/Desktop/airport_list/www.tianxun.com/list_all.txt";
		String toPath = "C:/Users/legion/Desktop/airport_list/www.tianxun.com/eth_airline.xlsx";
		String[] datas = TxtUtil.get(path);
		write("航司", new String[] { "二字码", "航司名称", "图标" }, datas, toPath);
	}

	public static String[][] read(String path) throws Exception {
		File file = new File(path);
		return read(file, 1);
	}

	public static void write(String title, String[] headers, String[] datas, String path) throws Exception {
		List<String[]> list = new ArrayList<String[]>();
		for (String row : datas) {
			String[] cells = row.split("@");
			list.add(cells);
		}
		write(title, headers, list.toArray(new String[list.size()][headers.length]), path);
	}

	public static void write(String title, String[] headers, String[][] datas, String path) throws Exception {
		File file = new File(path);
		// 声明一个工作薄
		XSSFWorkbook workbook = new XSSFWorkbook();
		// 生成一个表格
		Sheet sheet = workbook.createSheet(title);
		// 产生表格标题行
		Row row = sheet.createRow(0);
		for (int i = 0; i < headers.length; i++) {
			Cell cell = row.createCell(i);
			cell.setCellValue(headers[i]);
		}
		int rowIndex = 0;
		for (String[] fields : datas) {
			rowIndex++;
			row = sheet.createRow(rowIndex);
			for (int i = 0; i < fields.length; i++) {
				String field = fields[i];
				Cell cell = row.createCell(i);
				cell.setCellValue(field);
			}
		}
		workbook.write(new FileOutputStream(file));
	}

	public static void writeWithPic(String title, String[] headers, String[][] datas, String path) throws Exception {
		File file = new File(path);
		// 声明一个工作薄
		XSSFWorkbook workbook = new XSSFWorkbook();
		// 生成一个表格
		Sheet sheet = workbook.createSheet(title);
		// 声明一个画图的顶级管理器
		Drawing patriarch = sheet.createDrawingPatriarch();
		// anchor主要用于设置图片的属性
		XSSFClientAnchor anchor = new XSSFClientAnchor();
		anchor.setAnchorType(ClientAnchor.MOVE_AND_RESIZE);
		// 产生表格标题行
		Row row = sheet.createRow(0);
		for (int i = 0; i < headers.length; i++) {
			Cell cell = row.createCell(i);
			cell.setCellValue(headers[i]);
		}
		int rowIndex = 0;
		String picDir = "C:/Users/legion/Desktop/airport_list/www.tianxun.com/";
		BufferedImage bufferImg = null;
		for (String[] fields : datas) {
			rowIndex++;
			row = sheet.createRow(rowIndex);
			for (int i = 0; i < fields.length; i++) {
				String field = fields[i];
				Cell cell = row.createCell(i);
				if (field != null && field.contains("http")) {
					String picName = field.substring(field.lastIndexOf("/") + 1, field.length());
					// picName = "default.png";
					ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
					System.out.println(picDir + picName);
					bufferImg = ImageIO.read(new File(picDir + picName));
					ImageIO.write(bufferImg, "png", byteArrayOut);
					anchor.setDx1(0);
					anchor.setDy1(0);
					anchor.setDx2(0);
					anchor.setDy2(0);
					anchor.setCol1(2);
					anchor.setRow1(rowIndex - 1);
					anchor.setCol2(3);
					anchor.setRow2(rowIndex);
					cell.setAsActiveCell();
					// 插入图片
					patriarch
							.createPicture(anchor,
									workbook.addPicture(byteArrayOut.toByteArray(), XSSFWorkbook.PICTURE_TYPE_PNG))
							.resize(0.1);
				} else {
					cell.setCellValue(field);
				}
			}
		}
		workbook.write(new FileOutputStream(file));
	}

	public static void writeWithTemp(String title, String[][] datas, String path, String temp) throws Exception {
		File file = new File(path);
		File tempFile = new File(temp);
		// 声明一个工作薄
		Workbook workbook = WorkbookFactory.create(tempFile);
		// 生成一个表格
		Sheet sheet = workbook.getSheetAt(0);
		int rowIndex = 0;
		Row row = null;
		for (String[] fields : datas) {
			rowIndex++;
			row = sheet.createRow(rowIndex);
			for (int i = 0; i < fields.length; i++) {
				String field = fields[i];
				Cell cell = row.createCell(i);
				cell.setCellValue(field);
			}
		}
		workbook.write(new FileOutputStream(file));
	}

	public static void copyFile(File source, File target) throws Exception {
		InputStream fis = new BufferedInputStream(new FileInputStream(source));
		OutputStream fos = new BufferedOutputStream(new FileOutputStream(target));
		byte[] buf = new byte[4096];
		int i;
		while ((i = fis.read(buf)) != -1) {
			fos.write(buf, 0, i);
		}
		fis.close();
		fos.close();
	}

	public static Row getTempTitle(String temp) throws Exception {
		File file = new File(temp);
		Workbook wb = WorkbookFactory.create(file);
		Sheet st = wb.getSheetAt(1);
		return st.getRow(1);
	}

	/**
	 * 读取Excel的内容，第一维数组存储的是一行中格列的值，二维数组存储的是多少个行
	 * 
	 * @param file
	 *            读取数据的源Excel
	 * @param ignoreRows
	 *            读取数据忽略的行数，比喻行头不需要读入 忽略的行数为1
	 * @return 读出的Excel中数据的内容
	 * @throws FileNotFoundException
	 * @throws IOException
	 * @throws InvalidFormatException
	 */
	public static String[][] read(File file, int ignoreRows)
			throws FileNotFoundException, IOException, InvalidFormatException {
		List<String[]> result = new ArrayList<String[]>();
		int rowSize = 0;
		// 打开HSSFWorkbook
		Workbook wb = WorkbookFactory.create(file);
		Cell cell = null;
		for (int sheetIndex = 0; sheetIndex < wb.getNumberOfSheets(); sheetIndex++) {
			Sheet st = wb.getSheetAt(sheetIndex);
			// 第一行为标题，不取
			for (int rowIndex = ignoreRows; rowIndex <= st.getLastRowNum(); rowIndex++) {
				Row row = st.getRow(rowIndex);
				if (row == null) {
					continue;
				}
				int tempRowSize = row.getLastCellNum() + 1;
				if (tempRowSize > rowSize) {
					rowSize = tempRowSize;
				}
				String[] values = new String[rowSize];
				Arrays.fill(values, "");
				boolean hasValue = false;
				for (int columnIndex = 0; columnIndex <= row.getLastCellNum(); columnIndex++) {
					String value = "";
					cell = row.getCell(columnIndex);
					if (cell != null) {
						// 注意：一定要设成这个，否则可能会出现乱码
						// cell.setEncoding(HSSFCell.ENCODING_UTF_16);
						switch (cell.getCellType()) {
						case HSSFCell.CELL_TYPE_STRING:
							value = cell.getStringCellValue();
							break;
						case HSSFCell.CELL_TYPE_NUMERIC:
							if (HSSFDateUtil.isCellDateFormatted(cell)) {
								Date date = cell.getDateCellValue();
								if (date != null) {
									value = new SimpleDateFormat("yyyy-MM-dd").format(date);
								} else {
									value = "";
								}
							} else {
								value = new DecimalFormat("0").format(cell.getNumericCellValue());
							}
							break;
						case HSSFCell.CELL_TYPE_FORMULA:
							// 导入时如果为公式生成的数据则无值
							if (!cell.getStringCellValue().equals("")) {
								value = cell.getStringCellValue();
							} else {
								value = cell.getNumericCellValue() + "";
							}
							break;
						case HSSFCell.CELL_TYPE_BLANK:
							break;
						case HSSFCell.CELL_TYPE_ERROR:
							value = "";
							break;
						case HSSFCell.CELL_TYPE_BOOLEAN:
							value = (cell.getBooleanCellValue() == true ? "Y" : "N");
							break;
						default:
							value = "";
						}
					}
					values[columnIndex] = rightTrim(value);
					if (values[columnIndex] != null && !"".equals(values[columnIndex])) {
						hasValue = true;
					}
				}
				if (hasValue) {
					result.add(values);
				}
			}
		}
		String[][] returnArray = new String[result.size()][rowSize];
		for (int i = 0; i < returnArray.length; i++) {
			returnArray[i] = (String[]) result.get(i);
		}
		return returnArray;
	}

	/**
	 * 去掉字符串右边的空格
	 * 
	 * @param str
	 *            要处理的字符串
	 * @return 处理后的字符串
	 */
	public static String rightTrim(String str) {
		if (str == null) {
			return "";
		}
		int length = str.length();
		for (int i = length - 1; i >= 0; i--) {
			if (str.charAt(i) != 0x20) {
				break;
			}
			length--;
		}
		return str.substring(0, length);
	}
}